import { runCallback, isObject } from '@/utils/util'
import { colorDefault, colorGrayDefault } from '@/utils/config'

let toastTimer = ''
const wxToast = ({
  title = '',
  mask = true,
  icon = 'none',
  image = '',
  duration = 1500,
  onClose
} = {}) => {
  wx.showToast({
    title,
    icon,
    image,
    duration,
    mask,
    success: () => {
      clearTimeout(toastTimer)
      if (duration > 0 && typeof (onClose) === 'function') {
        toastTimer = setTimeout(() => {
          wx.hideToast()
          onClose()
        }, duration)
      }
    }
  })
}

function quickWxToast (e) {
  const { toast } = e.currentTarget.dataset

  if (!toast) return

  wxToast(toast)
}

wxToast.msg = (msg) => wxToast({title: msg})
wxToast.success = (msg) => wxToast({icon: 'success', title: msg})

const wxShowModal = ({
  title = '提示',
  content = '',
  showCancel = true,
  cancelText = '取消',
  cancelColor = colorGrayDefault,
  confirmText = '确定',
  confirmColor = colorDefault,
  editable = false,
  placeholderText = '',
  onConfirm,
  onCancel
} = {}) => {
  wx.showModal({
    title,
    content,
    showCancel,
    cancelText,
    cancelColor,
    confirmText,
    confirmColor,
    editable,
    placeholderText,
    success: res => {
      if (res.confirm) {
        runCallback(onConfirm, res.content)
      } else if (res.cancel) {
        runCallback(onCancel)
      }
    }
  })
}

function quickWxShowModal (e) {
  const { modal } = e.currentTarget.dataset

  if (!modal) return

  wxShowModal(modal)
}

const wxPay = (payInfo, succ, rej, succOri) => {
  wx.requestPayment({
    timeStamp: payInfo.timeStamp,
    nonceStr: payInfo.nonceStr,
    signType: 'MD5',
    paySign: payInfo.paySign,
    package: `prepay_id=${payInfo.prepay_id}`,
    success: res => {
      succOri && typeof succOri === 'function' && succOri(res)
      wxToast({
        title: '支付成功',
        onClose: succ ? succ.bind(this) : ''
      })
    },
    fail: err => {
      wxToast({
        title: '支付失败',
        onClose: rej ? rej.bind(this) : ''
      })
    }
  })
}

/**
 * 检查页面传参是否正确
 * @param {Array} vals 要检查的集合，如果内容为对象的话（{val, check}），val为检查值，check为检验值
 * @param {String} msg 提示
 */
function optErrorBack (vals = [], msg = '参数错误，请稍后重试') {
  return vals.some(item => {
    let flag = false

    if (isObject(item)) {
      flag = item.val === item.check
    } else {
      flag = typeof item === 'undefined' || item === null
    }

    if (flag) {
      wxToast({
        title: msg,
        onClose: () => {
          if (getCurrentPages().length === 1) {
            wx.switchTab({ url: '/pages/index/index' })
          } else {
            wx.navigateBack()
          }
        }
      })
    }

    return flag
  })
}

export {
  wxToast,
  wxShowModal,
  quickWxShowModal,
  quickWxToast,
  wxPay,
  optErrorBack
}